'use strict';

module.exports = () => {
  return async function(ctx, next) {
    if (ctx.session.userModel) {
      if (ctx.session.userModel.type === 'ADMIN') {
        await next();
      } else {
        const url = ctx.req.url;
        const method = ctx.req.method;
        let pathx = null;
        if (ctx.params && ctx.params.id) {
          const index = url.indexOf(ctx.params.id);
          const curl = url.substr(0, index);
          pathx = `${curl} ${method}`;
        } else {
          pathx = `${url} ${method}`;
        }
        const apiSet = new Set(ctx.session.userModel.role.apis);
        if (apiSet.has(pathx)) {
          await next();
        } else {
          throw new Error('不好意思，你没有权限访问这个接口')
        }
      }
    } else {
      const err = new Error('小子你确定登录了吗？');
      err.status = 401
      throw err
    }
  };
};
